<template>
  <view>
    <view class="profile-container" :class="{ 'mobile': isMobile }">
        <!-- 背景装饰 -->
        <view class="background-overlay"></view>
        
        <view class="profile-card slide-in-up">
            <view class="card-header">
                <view class="avatar-wrapper" @click="goToAvatarEditor">
                    <image :src="getAvatarUrl(userInfo.avatar)" class="avatar-canvas" />
                </view>
                <view class="user-identity">
                    <text class="username">{{ userInfo.name }}</text>
                    <text class="role-tag" :class="userInfo.role">
                        <i class="fas" :class="userInfo.role === 'admin' ? 'fa-user-shield' : 'fa-user'"></i>
                        {{ userInfo.role === 'admin' ? '管理员' : '普通用户' }}
                    </text>
                </view>
            </view>
            <view class="card-body">
                <view class="info-item">
                    <i class="info-icon fas fa-envelope"></i>
                    <text class="label">邮箱:</text>
                    <text class="value">{{ userInfo.email }}</text>
                </view>
                <view class="info-item">
                    <i class="info-icon fas fa-layer-group"></i>
                    <text class="label">等级:</text>
                    <text class="value">Lv.{{ userInfo.level || 1 }}</text>
                </view>
                <view class="info-item">
                    <i class="info-icon fas fa-calendar-alt"></i>
                    <text class="label">注册时间:</text>
                    <text class="value">{{ formatTime(userInfo.created_at) }}</text>
                </view>
            </view>
            <view class="card-footer">
                <button class="footer-btn edit-btn" @click="openEditModal">
                    <i class="fas fa-pencil-alt"></i> 编辑资料
                </button>
                <button class="footer-btn posts-btn" @click="goToMyPosts">
                    <i class="fas fa-rocket"></i> 我的动态
                </button>
            </view>
        </view>
    </view>
        
    <!-- 编辑资料弹窗 -->
    <uni-popup ref="editModal" type="center">
        <view class="edit-modal">
            <view class="modal-header">
                <text class="modal-title">编辑个人资料</text>
                <button class="close-btn" @click="closeEditModal"><i class="fas fa-times"></i></button>
            </view>
            <view class="modal-body">
                <view class="form-group">
                    <label class="form-label">昵称</label>
                    <input class="form-input" v-model="editableUserInfo.name" placeholder="请输入新的昵称" />
                </view>
            </view>
            <view class="modal-footer">
                <button class="modal-btn cancel" @click="closeEditModal">取消</button>
                <button class="modal-btn save" @click="saveProfile" :disabled="isSaving">
                    {{ isSaving ? '保存中...' : '保存' }}
                </button>
            </view>
        </view>
    </uni-popup>
  </view>
</template>

<script>
import { getUserInfo, updateUserInfo } from '@/api/user';
import { generateAvatarSvg } from '@/utils/avatar';
import UniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';
import { useUserStore } from '@/stores/user';

export default {
    components: {
        UniPopup
    },
    data() {
        return {
            userInfo: {
                name: '',
                email: '',
                level: 1,
                role: 'user',
                avatar: null,
                created_at: ''
            },
            editableUserInfo: {
                name: ''
            },
            isMobile: false,
            isSaving: false,
        };
    },
    onLoad() {
        const systemInfo = uni.getSystemInfoSync();
        this.isMobile = systemInfo.windowWidth < 768;
        const userStore = useUserStore();
        // 从Pinia状态同步用户信息
        if (Object.keys(userStore.$state).length > 0 && userStore.userName) {
            this.userInfo = {
                ...this.userInfo,
                ...userStore.$state
            };
        }
        this.fetchProfile();
    },
    methods: {
        getAvatarUrl(config) {
            return generateAvatarSvg(config);
        },
        async fetchProfile() {
            try {
                const userStore = useUserStore();
                if (userStore.userId) {
                    const data = await getUserInfo(userStore.userId);
                    this.userInfo = data;
                    // 更新Pinia中的用户信息
                    userStore.setUserInfo({...userStore.$state, ...data});
                } else {
                    uni.reLaunch({ url: '/pages/login/login' });
                }
            } catch (error) {
                console.error('获取用户信息失败', error);
                uni.showToast({ title: '加载失败', icon: 'none' });
            }
        },
        openEditModal() {
            this.editableUserInfo = { ...this.userInfo }; // 复制当前信息到编辑对象
            this.$refs.editModal.open();
        },
        closeEditModal() {
            this.$refs.editModal.close();
        },
        async saveProfile() {
            if (!this.editableUserInfo.name.trim()) {
                uni.showToast({ title: '昵称不能为空', icon: 'none' });
                return;
            }
            this.isSaving = true;
            try {
                const userId = uni.getStorageSync('userId');
                // 假设 updateUserInfo 接收用户ID和要更新的数据
                const updatedUser = await updateUserInfo(userId, { name: this.editableUserInfo.name });
                
                uni.showToast({ title: '保存成功', icon: 'success' });
                this.closeEditModal();
                this.userInfo = updatedUser;
                 // 更新本地存储的用户信息
                const userStore = useUserStore();
                 userStore.setUserInfo({...userStore.$state, ...updatedUser});

            } catch (error) {
                console.error('更新用户信息失败', error);
                uni.showToast({ title: '保存失败', icon: 'none' });
            } finally {
                this.isSaving = false;
            }
        },
        formatTime(timestamp) {
            if (!timestamp) return '未知时间';
            // 处理字符串类型的数字时间戳
            if (typeof timestamp === 'string' && !isNaN(timestamp)) {
                timestamp = Number(timestamp);
            }
            // 处理数字类型时间戳（秒级转毫秒）
            if (typeof timestamp === 'number') {
                // 检测是否为秒级时间戳（10位数字）
                if (timestamp.toString().length === 10) {
                    timestamp *= 1000;
                }
            }
            // 尝试直接解析时间戳，兼容更多格式
            let date = new Date(timestamp);
            if (isNaN(date.getTime())) {
                // 如果直接解析失败，尝试处理字符串格式
                timestamp = timestamp.replace(/-/g, '/').replace(' +0000 UTC', '');
              let date = new Date(timestamp);
                if (isNaN(date.getTime())) return '未知时间';
            }
            
            const now = new Date();
            const diff = now.getTime() - date.getTime();
            
            if (diff < 60000) return '刚刚';
            if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
            if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
            
            const year = date.getFullYear();
            const month = ('0' + (date.getMonth() + 1)).slice(-2);
            const day = ('0' + date.getDate()).slice(-2);
            return `${year}/${month}/${day} ${('0' + date.getHours()).slice(-2)}:${('0' + date.getMinutes()).slice(-2)}`;
        },
        goToAvatarEditor() {
            uni.navigateTo({ url: '/pages/avatar/avatar' });
        },
        goToMyPosts() {
            uni.navigateTo({ url: '/pages/my-posts/my-posts' });
        }
    }
};
</script>

<style scoped src="./profile.css"></style>